/*
   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package com.zavakid.scala.exercise.chapter3

import scala.util.Random
import scala.collection.mutable.ArrayBuffer
import scala.collection.mutable.ArrayBuilder
import scala.collection.mutable.Buffer

/**
 * @author zavakid 2013-6-7 下午6:31:57
 * @since 1.0
 */
object Main3 extends App {

  // 1
  def no1(n: Int): Array[Int] = {
    val random = new Random()
    val result: Array[Int] = new Array[Int](n)
    for (i <- 0 until n) {
      result(i) = random.nextInt(n)
    }
    result
  }

  // 2
  def no2(array: Array[Int]): Array[Int] = {
    array.grouped(2).flatMap(_.reverse).toArray
  }

  // 3
  def no3(array: Array[Int]): Array[Int] = {
    (for { a <- array.grouped(2); c <- a.reverse }
      yield c).toArray
  }

  //4
  def no4(array: Array[Int]): Array[Int] = {
    val a: ArrayBuffer[Int] = new ArrayBuffer();
    val b: ArrayBuffer[Int] = new ArrayBuffer()
    for (e <- array) {
      if (e > 0) a += e else b += e
    }
    a.appendAll(b)
    a.toArray
  }

  //5
  def no5(array: Array[Double]): Double = {
    array.max / array.length
  }

  //6
  def no6(array: Array[Int]): Array[Int] = {
    array.reverse
  }

  //7
  def no7(array: Array[Int]): Array[Int] = {
    array.distinct
  }

  // 8
  def no8(array: ArrayBuffer[Int]): ArrayBuffer[Int] = {
    val indexes = for (i <- 0 until array.length if array(i) < 0) yield i
    for (i <- 0 until indexes.drop(1).length by -1) array.remove(indexes(i))
    array
  }

  // 9
  def no9(): Array[String] = {
    import scala.collection.JavaConversions.asScalaBuffer
    import java.util.TimeZone
    val tzs: Array[String] = TimeZone.getAvailableIDs();
    val americaTzs = tzs.filter(_.startsWith("America/")).map(_.stripPrefix("America/"))
    americaTzs.sortWith(_ < _)
  }

  // 10
  def no10() = {
    import java.awt.datatransfer._
    val flavors = SystemFlavorMap.getDefaultFlavorMap().asInstanceOf[SystemFlavorMap]
    import scala.collection.JavaConversions.asScalaBuffer
    val result: Buffer[String] = flavors.getNativesForFlavor(DataFlavor.imageFlavor)
    result
  }

}